//index.js
//获取应用实例
import encode from '../../utils/base64.js';
import request from '../../utils/config.js';
import util from '../../utils/util.js';
let WXBizDataCrypt = require('../../utils/RdWXBizDataCrypt.js');
const app = getApp();

Page({
  data: {
    windowHeight: wx.getSystemInfoSync().windowHeight - 167,
    statusHeight: wx.getSystemInfoSync().windowHeight - 107,
    searchCheckHieght: wx.getSystemInfoSync().windowHeight - 100,
    pageNum: 1,
    totalPage: "",
    pageStatusNum: 1,
    totalStatusPage: "",
    defaultName: "",
    defaultImg: "",
    statusDefaultImg: "../../img/man.png",
    defaultDepart: "enforce",//执行("enforce"), 诉讼("lawsuit");
    menuTab: "list",//列表("list"),//关注("Attention"),//动态("Dynamic")
    loginUserInfo: "",
    attentionNum: "0",
    dynamicState: "0",
    toDoNum: "0",
    searchValue: "",
    caseList: [],
    charge: false,
    delBtnWidth: 180,//删除按钮宽度单位（rpx）
    showCaseList: true,
    showStatusList: false,
    showShareDocList: false,
    folderList:[],
    stateList: [],
    flagName: "",
    job: "",
    departmentList: [],
    level:0,//目录级别
    categoryIdList: [],//返回上级目录Id
    isFromOpenDoc: false,//打开文档返回后页面不要刷新
    isGetNextPage: false,
    isHidden:false,
    moreSearch_status:'',
    moreSearch_expireSign:'',
    toDoNumSlt:true,//控制待办列表是否高亮
    searchNum: 0,//搜索结果数量
    searchNumStatus: false,//搜索结果显示与隐藏
  },

  onPullDownRefresh: function () {
    this.setData({
      searchValue: "",
    });
    this.getStatusNum(this.data.defaultDepart);
    setTimeout(function () {
      wx.showToast({
        title: '加载成功',
        icon: 'success',
        duration: 1000
      })
      wx.stopPullDownRefresh();
    }, 1000); 
    console.log("执行了一次下拉刷新")
  },

  onLoad: function (options) {
    let flagName = options.flagName;
    let departmentList = wx.getStorageSync("departmentList");
    console.log("departmentList===", departmentList)
    if (flagName == "enforce"){
      this.setData({
        defaultDepart: flagName,
        flagName: "enforce",
        job: "执行跟踪",
        departmentList: JSON.parse(departmentList)
      });
    } else if (flagName == "lawsuit"){
      this.setData({
        defaultDepart: flagName,
        flagName: "lawsuit",
        job: "诉讼跟踪",
        departmentList: JSON.parse(departmentList)
      });
    }

    this.initEleWidth();
  },

  onShow: function () {
    console.log(app.globalData.listRefresh)
    if (app.globalData.listRefresh.SY && !app.globalData.listRefresh.SY.refresh) {
      this.getListItem()
      return
    }
    if (this.data.isFromOpenDoc) {
      this.setData({ isFromOpenDoc: false })
    } else {
      wx.hideShareMenu();
      this.setData({
        defaultName: app.globalData.userInfo.nickName,
        defaultImg: app.globalData.userInfo.avatarUrl
      });
      //开始校验看token值
      this.checkToken();
    }
  },
  getListItem() {
    let typeTab = this.data.menuTab;
    if (!app.globalData.listRefresh.SY.caseId) {
      return;
    }
    if (typeTab == "list" || typeTab == "charge") {
      let bodyInfo = {
        type: this.data.defaultDepart,
        operId: app.globalData.operId,
        pageNum: '1',
        pageSize: '10',
        roleType: this.data.charge ? 'self' : 'all',
        creditorName: this.data.searchValue || "",
        caseId: app.globalData.listRefresh.SY.caseId
      }
      let _this = this;
      console.log(bodyInfo)
      request.requestGetMis_api("flyWorkPlace/cases", wx.getStorageSync("token"), bodyInfo, (res) => {
        let agencyList = JSON.parse(res.data.body);
        console.log("获取待办事项列表成功caseId=caseId", agencyList)
        if (agencyList.length > 0) {
          agencyList[0].deadLine = util.timetrans(agencyList[0].deadLine, 'day');
          agencyList[0].txtStyle = "";
          if (agencyList[0].status === '2') {
            agencyList[0].img = "state2.png";
            agencyList[0].slt = "#a1a1a1";
          } else if (agencyList[0].status === '3') {
            agencyList[0].img = "state5.png";
            agencyList[0].slt = '#1aac19'
          } else if (agencyList[0].status === '4') {
            agencyList[0].img = "state4.png";
            agencyList[0].slt = '#1aac19'
          } else if (agencyList[0].status === '1') {
            agencyList[0].img = agencyList[0].expireSign == '1' ? 'state3.png' : 'state1.png';
            agencyList[0].slt = agencyList[0].expireSign == '1' ? '#ff6161' : '#58b5e1';
          }
          let caseList = _this.data.caseList;
          caseList[app.globalData.listRefresh.SY.itemIndex] = agencyList[0]
          _this.setData({
            caseList: caseList,
          });
        }
      }, (res) => {
        console.log("获取待办事件列表失败=", res)
      });
    } else if (typeTab == "Attention") {
      let bodyInfo = {
        type: this.data.defaultDepart,
        operId: app.globalData.operId,
        pageNum: '1',
        pageSize: '10',
        creditorName: this.data.searchValue || "",
        caseId: app.globalData.listRefresh.SY.caseId
      }
      console.log("flyWorkPlace/favorList", bodyInfo)
      let _this = this;
      request.requestGetMis_api("flyWorkPlace/favorList", wx.getStorageSync("token"), bodyInfo, (res) => {
        let agencyList = JSON.parse(res.data.body);
        console.log("获取关注列表成功caseId=caseId", agencyList)
        if (agencyList.length > 0) {
          agencyList[0].deadLine = util.timetrans(agencyList[0].deadLine, 'day');
          agencyList[0].txtStyle = "";
          if (agencyList[0].status === '2') {
            agencyList[0].img = "state2.png";
            agencyList[0].slt = "#a1a1a1";
          } else if (agencyList[0].status === '3') {
            agencyList[0].img = "state5.png";
            agencyList[0].slt = '#1aac19'
          } else if (agencyList[0].status === '4') {
            agencyList[0].img = "state4.png";
            agencyList[0].slt = '#1aac19'
          } else if (agencyList[0].status === '1') {
            agencyList[0].img = agencyList[0].expireSign == '1' ? 'state3.png' : 'state1.png';
            agencyList[0].slt = agencyList[0].expireSign == '1' ? '#ff6161' : '#58b5e1';
          }
          let caseList = _this.data.caseList;
          caseList[app.globalData.listRefresh.SY.itemIndex] = agencyList[0]
          _this.setData({
            caseList: caseList,
          });
        }
      }, (res) => {
        console.log("获取关注列表失败=", res)
      });
    } else if (typeTab == "all") {
      let bodyInfo = {
        pageNum: '1',
        pageSize: '10',
        creditorName: this.data.searchValue || "",
        status: this.data.moreSearch_status,
        expireSign: this.data.moreSearch_expireSign,
        caseId: app.globalData.listRefresh.SY.caseId
      }
      let _this = this;
      let defaultDepart = this.data.defaultDepart;
      let serviceName = "";//执行("enforce"), 诉讼("lawsuit");
      if (defaultDepart == "enforce") {
        serviceName = "enforceCurrInfos";
      } else if (defaultDepart == "lawsuit") {
        serviceName = "lawsuitCurrInfos";
      }
      console.log(bodyInfo)
      request.requestGetMis_api(serviceName, wx.getStorageSync("token"), bodyInfo, (res) => {
        let agencyList = JSON.parse(res.data.body);
        console.log("查询执行/诉讼列表成功caseId=caseId", agencyList)
        if (agencyList.length > 0) {
          agencyList[0].deadLine = util.timetrans(agencyList[0].deadLine, 'day');
          agencyList[0].txtStyle = "";
          if (agencyList[0].status === '2') {
            agencyList[0].img = "state2.png";
            agencyList[0].slt = "#a1a1a1";
          } else if (agencyList[0].status === '3') {
            agencyList[0].img = "state5.png";
            agencyList[0].slt = '#1aac19'
          } else if (agencyList[0].status === '4') {
            agencyList[0].img = "state4.png";
            agencyList[0].slt = '#1aac19'
          } else if (agencyList[0].status === '1') {
            agencyList[0].img = agencyList[0].expireSign == '1' ? 'state3.png' : 'state1.png';
            agencyList[0].slt = agencyList[0].expireSign == '1' ? '#ff6161' : '#58b5e1';
          }
          let caseList = _this.data.caseList;
          caseList[app.globalData.listRefresh.SY.itemIndex] = agencyList[0]
          _this.setData({
            caseList: caseList,
          });
        }
      }, (res) => {
        wx.hideLoading()
        console.log("查询执行列表失败=", res)
      });
    }
  },
  //检验token值
  checkToken: function () {
    let _that = this;
    app.checkGlobalToken(function (res) {
      _that.setData({
        loginUserInfo: res.loginUserInfo,
      });
      let tempList = res.tempList;
      let flagName = res.flagName;
      let jurisdiction = res.jurisdiction;
      let roleQuanxian = res.roleQuanxian;
      let department = res.department;
      if (tempList.length == 0) {
        wx.showModal({
          title: '对不起',
          content: '您的权限不足',
          confirmText: "知道了",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../index/index',
              })
            } else if (res.cancel) {

            }
          }
        })
        return;
      }

      //校验上次记住的部门权限是否还存在
      if (jurisdiction.indexOf(roleQuanxian) < 0) {
        wx.showModal({
          title: '对不起',
          content: "您的" + department + "部门权限不足,请重新登录并选择相关部门",
          confirmText: "知道了",
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.redirectTo({
                url: '../index/index',
              })
            } else if (res.cancel) {
            }
          }
        })
        return;
      }
      _that.getStatusNum(_that.data.defaultDepart);
    }, function (res) {
      //登录超时
      wx.showModal({
        title: '登录超时',
        content: '点击确定重新登录',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            wx.redirectTo({
              url: '../index/index',
            })
          } else if (res.cancel) {
          }
        }
      })
    });
  },

  //获取动态数量
  getStatusNum: function (type, flag) {
    let bodyInfo = {
      type: type
    }
    let _this = this;
    request.requestGetMis_api("flyWorkPlace", wx.getStorageSync("token"), bodyInfo, (res) => {
      console.log("动态数量成功=", res)
      let bodyList = JSON.parse(res.data.body);
      let attentionNum = "0";
      let dynamicState = "0";
      let toDoNum = '0';
      bodyList.forEach(function (e) {
        if (e.trips == '我的收藏') {
          attentionNum = e.number + "";
        } else if (e.trips == '最新动态') {
          dynamicState = e.number + "";
        } else if (e.trips == "待办列表") {
          toDoNum = e.number + "";
        }
      });
      _this.setData({
        attentionNum: attentionNum,
        dynamicState: dynamicState,
        toDoNum: toDoNum
      });

      //列表("list"),//关注("Attention"),//动态("Dynamic")
      let typeTab = _this.data.menuTab;
      if (flag != "gz") {
        if (typeTab == "list" || typeTab == "charge") {
          _this.getAgencyCaseList(type, 1);
        } else if (typeTab == "Attention") {
          _this.getAttentionList(type, 1);
        } else if (typeTab == "all") {
          _this.CurrInfosListQuery(1);
        } else if (typeTab == "Dynamic") {
          _this.getDynamicList(type, 1);
        } else if (typeTab == "ShareDoc") {
          _this.getCategoryList(0,'', 1);
        }
      }
    }, (res) => {
      console.log("动态数量失败=", res)
    });
  },


  //查询待办事项列表
  getAgencyCaseList: function (type, pageNum) {
    if (pageNum == 1) {
      this.setData({
        caseList: new Array(),
        searchNum: 0
      });
    }
    let bodyInfo = {
      type: type,
      operId: app.globalData.operId,
      pageNum: pageNum,
      pageSize: '10',
      roleType: this.data.charge ?'self':'all',
      creditorName: this.data.searchValue || "",
    }
    let _this = this;
    console.log(bodyInfo)
    request.requestGetMis_api("flyWorkPlace/cases", wx.getStorageSync("token"), bodyInfo, (res) => {
      let agencyList = JSON.parse(res.data.body);
      console.log("获取待办事项列表成功=", agencyList)
      if (pageNum == 1 && JSON.parse(res.data.body).length == 0) {
        wx.showToast({ title: '暂无数据', icon: 'none', duration: 1000 });
      }
      if (agencyList.length > 0) {
        agencyList.forEach(function (e) {
          e.deadLine = util.timetrans(e.deadLine, 'day');
          e.txtStyle = "";
          if (e.status === '2') {
            e.img = "state2.png";
            e.slt = "#a1a1a1";
          } else if (e.status === '3') {
            e.img = "state5.png";
            e.slt = '#1aac19'
          } else if (e.status === '4') {
            e.img = "state4.png";
            e.slt = '#1aac19'
          } else if (e.status === '1') {
            e.img = e.expireSign == '1' ? 'state3.png' : 'state1.png';
            e.slt = e.expireSign == '1' ? '#ff6161' : '#58b5e1';
          }
        });
        let tempList = _this.data.caseList;
        for (var i = 0; i < agencyList.length; i++) {
          tempList.push(agencyList[i]);
        }
        _this.setData({
          caseList: tempList,
          pageNum: pageNum,
          totalPage: res.data.totalPage,
          searchNum: res.data.totalNum
        });
      }
    }, (res) => {
      console.log("获取待办事件列表失败=", res)
    });
  },

  //****************************************滚动控制区域开始***************************************//
  //滚动到顶部
  upper: function (e) {
    // console.log("顶部=",e)
  },

  //滚动到底部
  lower: function (e) {
    console.log("底部=", e)
    let pageNum = this.data.pageNum;
    let totalPage = this.data.totalPage;
    // console.log("pageNum===", pageNum)
    console.log("totalPage====pageNum", totalPage, '=====', pageNum)
    if (pageNum < totalPage) {
      let typeTab = this.data.menuTab;
      if (typeTab == "list" || typeTab == "charge") {
        this.getAgencyCaseList(this.data.defaultDepart, pageNum * 1 + 1)
      } else if (typeTab == "all") {
        this.CurrInfosListQuery(pageNum * 1 + 1);
      } else if (typeTab == "Attention") {
        this.getAttentionList(this.data.defaultDepart, pageNum * 1 + 1);
      }
    } else {
      //显示没有更多字样
    }
  },

  //滚动到最新动态顶部
  upperStatus: function (e) {
    // console.log("顶部=", e)
  },

  //滚动最新动态到底部
  lowerStatus: function (e) {
    console.log("最新动态底部=", e)
    let pageStatusNum = this.data.pageStatusNum;
    let totalStatusPage = this.data.totalStatusPage;
    // console.log("pageStatusNum===", pageStatusNum)
    // console.log("totalStatusPage====", totalStatusPage)
    if (pageStatusNum < totalStatusPage) {
      this.getDynamicList(this.data.defaultDepart, pageStatusNum*1+1)
    } else {
      //显示没有更多字样
    }
  },

  //滚动触发
  // scroll: function (e) {
  //   console.log("滚动触发=",e)
  // },

  //****************************************滚动控制区域结束***************************************//

  //获取搜索查询值
  getSearchValue: function (e) {
    var searchValue = e.detail.value;
    this.setData({
      searchValue: searchValue
    });
  },
  delSearchValue: function () {
    this.setData({
      searchValue: ''
    });
  },

  //开始调用查询接口
  startSearchFun: function () {
    // wx.navigateTo({
    //   url: '../SuSong/ssIndex/ssIndex',
    // })
    let value = this.data.searchValue || "";
    this.setData({
      searchNumStatus: true,
      charge:false,
    })
    if (this.data.menuTab == 'charge' || this.data.menuTab == 'list' || this.data.menuTab == 'all' || this.data.menuTab == 'Attention') {
      if (this.data.isHidden) {
        this.setData({
          isHidden: false,
        })
        if (this.data.menuTab == 'Attention') {
          this.setData({
            toDoNumSlt: false,
          })
          this.getAttentionList(this.data.defaultDepart, 1);
        } else if (this.data.menuTab == 'all') {
          this.setData({
            toDoNumSlt: false,
          })
          this.CurrInfosListQuery(1);
        } else if (this.data.menuTab == 'list') {
          this.setData({
            toDoNumSlt: true,
          })
          this.getAgencyCaseList(this.data.defaultDepart, 1)
        } else if (this.data.menuTab == 'charge') {
          this.setData({
            charge: true,
          })
          this.getAgencyCaseList(this.data.defaultDepart, 1)
        }
      } else {
        this.setData({ isHidden: true,})
      }
    }
  },
  searchSign:function(e){
    this.setData({
      isHidden: false,
      toDoNumSlt: false,
      searchValue: "",
      searchNumStatus: true,
      charge: false,
    }); 
    if (e.currentTarget.dataset.sign == 'Attention') {
      this.setData({
        moreSearch_status: '',
        moreSearch_expireSign: '',
        menuTab:'Attention',
      })
      this.getAttentionList(this.data.defaultDepart, 1);
    } else if (e.currentTarget.dataset.sign == 'all') {
      this.setData({
        moreSearch_status: '',
        moreSearch_expireSign: '',
        menuTab: 'all',
      })
      this.CurrInfosListQuery(1);
    } else if (e.currentTarget.dataset.sign == 'deal') {
      this.setData({
        moreSearch_status: '',
        moreSearch_expireSign: '',
        menuTab: 'list',
        toDoNumSlt: true,
      })
      this.getAgencyCaseList(this.data.defaultDepart, 1)
    } else if (e.currentTarget.dataset.sign == 'charge') {
      this.setData({
        moreSearch_status: '',
        moreSearch_expireSign: '',
        menuTab: 'charge',
        charge: true,
      })
      this.getAgencyCaseList(this.data.defaultDepart, 1)
    } else if (e.currentTarget.dataset.sign == '1' || e.currentTarget.dataset.sign == '2' || e.currentTarget.dataset.sign == '3' || e.currentTarget.dataset.sign == '4') {
      this.setData({
        moreSearch_status: e.currentTarget.dataset.sign,
        moreSearch_expireSign: '',
        menuTab: 'all',
      })
      this.CurrInfosListQuery(1);
    } else if (e.currentTarget.dataset.sign == 'expire') {
      this.setData({
        moreSearch_status: '',
        moreSearch_expireSign: '1',
        menuTab: 'all',
      })
      this.CurrInfosListQuery(1);
    }
  },
  isHiddenChange: function () {
    if (this.data.menuTab == 'list' || this.data.menuTab == 'all' || this.data.menuTab == 'Attention' || this.data.menuTab == 'charge' ) {
      this.setData({ isHidden: true, searchNumStatus: false})
    } 
  },
  cancelSearch: function () {
    this.setData({ isHidden: false})
  },
  //待办列表查询
  CurrInfosListQuery: function (pageNum) {
    if (pageNum == 1) {
      this.setData({
        caseList: new Array(),
        searchNum: 0
      });
    }
    wx.showLoading({
      title: '正在加载……', mask: true
    })
    let bodyInfo = {
      pageNum: pageNum,
      pageSize: '10',
      creditorName: this.data.searchValue || "",
      status:this.data.moreSearch_status,
      expireSign: this.data.moreSearch_expireSign,
    }
    let _this = this;
    let defaultDepart = this.data.defaultDepart;
    let serviceName = "";//执行("enforce"), 诉讼("lawsuit");
    if (defaultDepart == "enforce") {
      serviceName = "enforceCurrInfos";
    } else if (defaultDepart == "lawsuit") {
      serviceName = "lawsuitCurrInfos";
    }
    console.log(bodyInfo)
    request.requestGetMis_api(serviceName, wx.getStorageSync("token"), bodyInfo, (res) => {
      console.log("查询执行/诉讼列表成功=", res)
      wx.hideLoading()
      let agencyList = JSON.parse(res.data.body);
      if (pageNum == 1 && JSON.parse(res.data.body).length == 0) {
        wx.showToast({ title: '暂无数据', icon: 'none', duration: 1000 });
      }
      if (agencyList.length > 0) {
        agencyList.forEach(function (e) {
          e.deadLine = util.timetrans(e.deadLine, 'day');
          e.txtStyle = "";
          if (e.status === '2') {
            e.img = "state2.png";
            e.slt = "#a1a1a1";
          } else if (e.status === '3') {
            e.img = "state5.png";
            e.slt = '#1aac19'
          } else if (e.status === '4') {
            e.img = "state4.png";
            e.slt = '#1aac19'
          } else if (e.status === '1') {
            e.img = e.expireSign == '1' ? 'state3.png' : 'state1.png';
            e.slt = e.expireSign == '1' ? '#ff6161' : '#58b5e1';
          }
        });
        let tempList = _this.data.caseList;
        for (var i = 0; i < agencyList.length; i++) {
          tempList.push(agencyList[i]);
        }

        _this.setData({
          caseList: tempList,
          pageNum: pageNum,
          totalPage: res.data.totalPage,
          searchNum: res.data.totalNum
        });
      }
    }, (res) => {
      wx.hideLoading()
      console.log("查询执行列表失败=", res)
    });
  },

  //****************************************组件回调区域开始***************************************//

  //回调选择部门函数
  _selectDepart: function (e) {
    let departName = e.detail;
    this.setData({
      defaultDepart: departName,
      menuTab: "list",
      showCaseList: true,
      showStatusList: false,
      showShareDocList: false,
      searchValue: "",
      //置空
      isHidden: false,
      moreSearch_status: '',
      moreSearch_expireSign: '',
      searchNum: 0,//搜索结果数量
    });
    this.getStatusNum(departName);
  },

  //回调去代办列表页面
  _goAgencyPage: function (e) {
    let departName = e.detail.split("|")[0];
    let menuTab = e.detail.split("|")[1];
    this.setData({
      searchValue: ""
    });
    this.setData({
      menuTab: menuTab,
      showCaseList: true,
      showStatusList: false,
      showShareDocList: false,
    });
    // this.getStatusNum(departName);
    this.getAgencyCaseList(departName, 1);
  },

  //回调去我的关注界面
  _goMonitoring: function (e) {
    app.globalData.listRefresh.SY = {
      refresh: false,
    }
    let departName = e.detail.split("|")[0];
    let menuTab = e.detail.split("|")[1];
    this.setData({
      searchValue: ""
    });
    this.setData({
      menuTab: menuTab,
      showCaseList: true,
      showStatusList: false,
      showShareDocList: false,
    });
  }, 
//文档库
  _goShareDoc: function (e) {
    let departName = e.detail.split("|")[0];
    let menuTab = e.detail.split("|")[1];
    this.setData({
      searchValue: ""
    });
    this.setData({
      menuTab: menuTab,
      showCaseList: false,
      showStatusList: false,
      showShareDocList:true,
    });
    this.getCategoryList(0,"",1);
  },
  //回调去最新动态界面
  _goState: function (e) {
    let departName = e.detail.split("|")[0];
    let menuTab = e.detail.split("|")[1];
    this.setData({
      searchValue: ""
    });
    this.setData({
      menuTab: menuTab,
      showCaseList: false,
      showStatusList: true,
      showShareDocList: false,
    });
    this.getDynamicList(departName, 1);
  },

  //****************************************组件回调区域结束***************************************//

  // 查询我的最新动态列表
  getDynamicList: function (type, pageNum) {
    if (pageNum==1) {
      this.setData({
        stateList: new Array()
      });
    }
    let bodyInfo = {
      type: type,
      operId: app.globalData.operId,
      pageNum: pageNum,
      pageSize: '10'
    }
    wx.showLoading({
      title: '加载中...', mask: true
    })
    let _this = this;
    console.log("bodyInfo======", bodyInfo)
    request.requestGetMis_api("flyWorkPlace/dynamics", wx.getStorageSync("token"), bodyInfo, (res) => {
      console.log("获取最新动态列表成功=", JSON.parse(res.data.body))
      wx.hideLoading();
      let dynamicsList = JSON.parse(res.data.body);
      dynamicsList.forEach(function (e) {
        e.status = util.checkStatus(e.status);
        // e.time = util.formatDate(e.applyDate + e.applyTime)
        e.time = util.timetrans(e.finishTime)
      });
      let tempList = _this.data.stateList;
      for (var i = 0; i < dynamicsList.length; i++) {
        tempList.push(dynamicsList[i]);
      }
      if (pageNum == 1 && JSON.parse(res.data.body).length==0) {
        wx.showToast({ title: '暂无数据', icon: 'none', duration: 1000 });
      }
      _this.setData({
        stateList: tempList,
        pageStatusNum: pageNum,
        totalStatusPage: res.data.totalPage
      });
    }, (res) => {
      wx.hideLoading();
      console.log("获取最新动态列表失败=", res)
    });
  },

  // 查询我的关注列表
  getAttentionList: function (type, pageNum) {
    if (pageNum == 1) {
      this.setData({
        caseList: new Array(),
        searchNum: 0
      });
    }
    wx.showLoading({
      title: '加载中...', mask: true
    })
    let bodyInfo = {
      type: type,
      operId: app.globalData.operId,
      pageNum: pageNum,
      pageSize: '10',
      creditorName: this.data.searchValue || ""
    }
    console.log("flyWorkPlace/favorList",bodyInfo)
    let _this = this;
    request.requestGetMis_api("flyWorkPlace/favorList", wx.getStorageSync("token"), bodyInfo, (res) => {
      console.log("获取关注列表成功=", res)
      wx.hideLoading();
      let agencyList = JSON.parse(res.data.body);
      if (pageNum == 1 && JSON.parse(res.data.body).length == 0) {
        wx.showToast({ title: '暂无数据', icon: 'none', duration: 1000 });
      }
      if (agencyList.length > 0) {
        agencyList.forEach(function (e) {
          e.deadLine = util.timetrans(e.deadLine, 'day');
          e.txtStyle = "";
          e.isFavor = 'Y';
          if (e.status === '2') {
            e.img = "state2.png";
            e.slt = "#a1a1a1";
          } else if (e.status === '3') {
            e.img = "state5.png";
            e.slt = '#1aac19'
          } else if (e.status === '4') {
            e.img = "state4.png";
            e.slt = '#1aac19'
          } else if (e.status === '1') {
            e.img = e.expireSign == '1' ? 'state3.png' : 'state1.png';
            e.slt = e.expireSign == '1' ? '#ff6161' : '#58b5e1';
          }
        });
        let tempList = _this.data.caseList;
        for (var i = 0; i < agencyList.length; i++) {
          tempList.push(agencyList[i]);
        }
        _this.setData({
          caseList: tempList,
          pageNum: pageNum,
          totalPage: res.data.totalPage,
          searchNum:res.data.totalNum
        });
      }
    }, (res) => {
      wx.hideLoading();
      console.log("获取关注列表失败=", res)
    });
  },
  //-----------文档库-----------
  getCategoryList: function (level, categoryId,pageNum){
    wx.showLoading({
      title: '加载中...', mask: true
    })
    this.setData({
      folderList: [],
      level: level,
      isGetNextPage: true,
    })
    if (pageNum == 1) {
      this.setData({
        docList: [],
      });
    }
    if (level == 'none') {
      this.getDocList(categoryId, pageNum);
      return;
    }
    let bodyInfo = { level: level }
    if (categoryId && categoryId != 'none' && level!='0'){
      bodyInfo.parentId = categoryId;
    }
    console.log("shareCategorys", bodyInfo)
    let _this = this;
    request.requestMisApi("get","shareCategorys", bodyInfo, (res) => {
      wx.hideLoading();
      if (res.code == '00') {
        console.log("获取文档目录成功=", JSON.parse(res.body))
        _this.setData({
          folderList: JSON.parse(res.body),
        });
        if (categoryId){
          _this.getDocList(categoryId, pageNum);
        }else{
          _this.setData({
            docList: [],
            isGetNextPage: false,
          });
        }
      }else{
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    }, (res) => {
      wx.hideLoading();
      console.log("获取文档目录成功=", res)
    });
  },
  getDocList: function (categoryId, pageNum){
    wx.showLoading({
      title: '加载中...',mask: true
    })
    let bodyInfo = {
      docFileName: this.data.searchValue || "",
      pageNum: pageNum,
      pageSize:'10'
    }
    if(categoryId!='none'){
      bodyInfo.categoryId = categoryId
    }
    console.log("shareDocs", bodyInfo)
    let _this = this;
    request.requestMisApi("get", "shareDocs", bodyInfo, (res) => {
      wx.hideLoading();
      if (res.code == '00') {
        console.log("获取文档成功=", JSON.parse(res.body))
        let docList = this.data.docList;
        JSON.parse(res.body).forEach((item)=>{
          item.sizeDesc = item.docSize * 1 < 1024 ? item.docSize + 'KB' : (item.docSize / 1024).toFixed(2) + 'MB';
          item.timeDesc = util.dateStr(item.uploadDate);
          if (/.doc$/.test(item.docFileName) || /.docx$/.test(item.docFileName)){
            item.iconImg ='file_word';
            item.canOpen=true;
          } else if (/.xls$/.test(item.docFileName) || /.xlsx$/.test(item.docFileName)) {
            item.iconImg = 'file_exl';
            item.canOpen = true;
          } else if (/.zip$/.test(item.docFileName)) {
            item.iconImg = 'file_zip'
          } else if (/.png$/.test(item.docFileName)){
            item.iconImg = 'file_png';
            item.canOpen = true;
          } else if (/.exe$/.test(item.docFileName)) {
            item.iconImg = 'file_exe'
          } else if (/.gif$/.test(item.docFileName)) {
            item.iconImg = 'file_gif'
          } else if (/.jpg$/.test(item.docFileName) || /.jpeg$/.test(item.docFileName)) {
            item.iconImg = 'file_jpg';
            item.canOpen = true;
          } else if (/.ios$/.test(item.docFileName)) {
            item.iconImg = 'file_ios'
          } else if (/.pdf$/.test(item.docFileName)) {
            item.iconImg = 'file_pdf';
            item.canOpen = true;
          } else if (/.ppt$/.test(item.docFileName) || /.pptx$/.test(item.docFileName)) {
            item.iconImg = 'file_ppt';
            item.canOpen = true;
          } else if (/.txt$/.test(item.docFileName)) {
            item.iconImg = 'file_txt';
          }else{
            item.iconImg = 'file_other'
          }
          docList.push(item)
        })
        _this.setData({
          docList: docList,
          pageDocNum: pageNum,
          totalDocPage: res.totalPage
        });
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
      _this.setData({
        isGetNextPage: false,
      });
    }, (res) => {
      _this.setData({
        isGetNextPage: false,
      });
      wx.hideLoading();
      console.log("获取文档成功=", res)
    });
  },
  folderClick:function(e){
    console.log(e)
    let category = e.currentTarget.dataset.category;
    this.setData({ categoryId: this.data.categoryIdList.push(category.categoryId)})
    this.getCategoryList(category.level * 1 + 1, category.categoryId, 1)
  },
  folderBack: function () {
    if (this.data.level == 'none') {
      this.getCategoryList(0, this.data.categoryIdList[this.data.categoryIdList.length - 2], 1)
    } else {
      this.getCategoryList(this.data.level * 1 - 1, this.data.categoryIdList[this.data.categoryIdList.length - 2], 1)
    }
    this.setData({ categoryId: this.data.categoryIdList.pop() })
  },
  shareDocSearch:function(){
    if (this.data.searchValue) {
      this.setData({ categoryId: this.data.categoryIdList.push('none') })
      this.getCategoryList('none', 'none', 1)
    }
  },
  lowerShareDoc:function(){
    let pageDocNum = this.data.pageDocNum;
    let totalDocPage = this.data.totalDocPage;
    if (pageDocNum < totalDocPage && !this.data.isGetNextPage) {
      this.getCategoryList(this.data.level, this.data.categoryIdList[this.data.categoryIdList.length - 1], pageDocNum*1+1)
    } else {
      //显示没有更多字样
    }
  },
  docClick(e){
    let doc = e.currentTarget.dataset.doc
    if (doc.canOpen){
      this.dowmloadFile(doc.docUrl, doc.docFileName)
    } else{
      wx.setClipboardData({
        data: doc.docUrl,
        success: function (res) {
          console.log(res)
          wx.showToast({
            title: '复制链接成功',
            icon: 'success',
            duration: 700
          })
          setTimeout(() => {
            wx.showModal({
              content: '该文件无法预览，文件路径已复制到剪切板，你可以打开浏览器下载',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })
          },700)
        }
      })
    }
  },
  docLongpress: function (e) {
    let doc = e.currentTarget.dataset.doc
    wx.setClipboardData({
      data: doc.docUrl,
      success: function (res) {
        console.log(res)
        wx.showToast({
          title: '复制链接成功',
          icon: 'success',
          duration: 800
        })
      }
    })
  },
  //点击下载文件
  dowmloadFile: function (fileurl, docName) {
    let _this=this;
    let tempSuf = docName.split('.');
    let suffix = tempSuf[tempSuf.length - 1];
    let fileType = "doc,xls,ppt,pdf,docx,xlsx,pptx";
    let picSuffix = "bmp,jpg,png,tiff,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,jpeg";
    console.log("fileurl==", fileurl, docName)
    wx.showLoading({ title: ' ', mask: true })
    wx.downloadFile({
      url: fileurl, //仅为示例，并非真实的资源
      success: function (res) {
        // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
        console.log("读取文件成功=", res)
        // if (res.statusCode === 200) {
        var filePath = res.tempFilePath
        wx.hideLoading()
        _this.setData({ isFromOpenDoc:true})
        if (fileType.indexOf(suffix) != "-1") {
          wx.openDocument({
            filePath: filePath,
            success: function (res) {
              console.log('打开文档成功')
            }
          })
        } else if (picSuffix.indexOf(suffix.toLowerCase()) != "-1") {
          wx.previewImage({
            current: filePath, // 当前显示图片的http链接
            urls: [filePath] // 需要预览的图片http链接列表
          })
        }
      },
      fail: function (res) {
        wx.hideLoading()
        console.log("读取文件失败=", res);
      }
    })
  },
  goDetail: function (e) {
    let caseInfo = e.currentTarget.dataset.caseinfo;
    app.globalData.caseDetailData = caseInfo;
    app.globalData.listRefresh.SY = {
      refresh: false,
      caseId: caseInfo.caseId,
      itemIndex: e.currentTarget.dataset.index,
      tabtype: e.currentTarget.dataset.tabtype
    }
    console.log("案件详情=",caseInfo);
    if (this.data.defaultDepart == "enforce") {
      wx.navigateTo({
        url: '../enforceDetail/enforceDetail',
      })
    } else if (this.data.defaultDepart == "lawsuit") {
      wx.navigateTo({
        url: '../lawsuitDetail/lawsuitDetail',
      })
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.top = this.selectComponent("#topper");
  },

  touchS: function (e) {
    if (e.touches.length == 1) {
      this.setData({
        //设置触摸起始点水平方向位置
        startX: e.touches[0].clientX,
        startY: e.touches[0].clientY,
      });
    }
  },

  touchM: function (e) {
    if (e.touches.length == 1) {
      //手指移动时水平方向位置
      let moveX = e.touches[0].clientX;
      let moveY = e.touches[0].clientY;
      //手指起始点位置与移动期间的差值
      let disY = this.data.startY - moveY;
      let disX = this.data.startX - moveX;
      let delBtnWidth = this.data.delBtnWidth;
      let txtStyle = "";
      // if (Math.abs(disY * 1) > 20) {
      //   txtStyle = "left:0px";
      // }else{
        if (disX == 0 || disX < 0) {//如果移动距离小于等于0，文本层位置不变
          txtStyle = "left:0px";
        } else if (disX > 100 && Math.abs(disY * 1)< 20) {//移动距离大于0，文本层left值等于手指移动距离
          txtStyle = "left:-" + disX + "px";
          if (disX >= delBtnWidth) {
            //控制手指移动距离最大值为删除按钮的宽度
            txtStyle = "left:-" + delBtnWidth + "px";
          }
        }
      // }
      

      //获取手指触摸的是哪一项
      var index = e.currentTarget.dataset.index;
      var list = this.data.caseList;
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        caseList: list
      });
    }
  },

  touchE: function (e) {
    if (e.changedTouches.length == 1) {
      //手指移动结束后水平位置
      let endX = e.changedTouches[0].clientX;
      //触摸开始与结束，手指移动的距离
      let disX = this.data.startX - endX;
      let delBtnWidth = this.data.delBtnWidth;
      //如果距离小于删除按钮的1/2，不显示删除按钮
      let txtStyle = disX > delBtnWidth / 2 ? "left:-" + delBtnWidth + "px" : "left:0px";
      //获取手指触摸的是哪一项
      let index = e.currentTarget.dataset.index;
      let list = this.data.caseList;
      if (txtStyle != "left:0px") {
        list.forEach(function (e) {
          e.txtStyle = "";
        });
      }
      list[index].txtStyle = txtStyle;
      //更新列表的状态
      this.setData({
        caseList: list
      });
    }
  },

  //获取元素自适应后的实际宽度
  getEleWidth: function (w) {
    let real = 0;
    try {
      let res = wx.getSystemInfoSync().windowWidth;
      let scale = (750 / 2) / (w / 2);//以宽度750px设计稿做宽度的自适应
      // console.log(scale);
      real = Math.floor(res / scale);
      return real;
    } catch (e) {
      return false;
      // Do something when catch error
    }
  },

  //初始化宽度
  initEleWidth: function () {
    let delBtnWidth = this.getEleWidth(this.data.delBtnWidth);
    this.setData({
      delBtnWidth: delBtnWidth
    });
  },

  //点击关注
  attentionItem: function (e) {
    let index = e.currentTarget.dataset.index;
    let list = this.data.caseList;
    let caseId = list[index].caseId;
    if (list[index].isFavor == "N") {
      // 开始关注
      let bodyInfo = {
        caseId: caseId
      }
      let _this = this;
      request.requestGetMis_api("flyWorkPlace/favorCases/" + caseId, wx.getStorageSync("token"), bodyInfo, (res) => {
        console.log("收藏成功=", res)
        list[index].isFavor = "Y";
        list[index].txtStyle = "";
        _this.setData({
          caseList: list
        });
        // wx.showToast({
        //   title: '收藏成功',
        //   icon: 'success',
        //   duration: 2000
        // })
        _this.getStatusNum(_this.data.defaultDepart, "gz")
      }, (res) => {
        console.log("收藏失败=", res)
      });
    } else {
      //取消关注
      let bodyInfo = {
        caseId: caseId
      }
      let _this = this;
      request.requestGetMis_api("flyWorkPlace/unfavorCases/" + caseId, wx.getStorageSync("token"), bodyInfo, (res) => {
        console.log("取消收藏成功=", res)
        // if (_this.data.menuTab == "Attention") {
        //   list.splice(index, 1);
        // } else {
        //   list[index].isFavor = "N";
        //   list[index].txtStyle = "";
        // }
        list[index].isFavor = "N";
        list[index].txtStyle = "";
        _this.setData({
          caseList: list
        });
        _this.getStatusNum(_this.data.defaultDepart, "gz")
      }, (res) => {
        console.log("取消收藏失败=", res)
      });
    }
  },



  //转发
  // onShareAppMessage: function(res){

  // }
})
